import { lazyBatchReport } from '../report/index'

/**
 * 前端静态资源的统计
 */
export function observeEvent() {
  const entryHandler = (entryList) => {
    const entries = entryList.getEntries()
    for (const entry of entries) {
      if (observer) {
        observer.disconnect()
      }

      const reportData = {
        name: entry.name, // 资源的名字
        type: 'performance', // 类型
        subType: entry.entryType, //类型
        sourceType: entry.initiatorType, //资源类型
        duration: entry.duration, // 加载时间
        dns: entry.domainLookupEnd - entry.domainLookupstart, // dns解折时间
        tcp: entry.connectEnd - entry.connectstart, // tcp连接时间
        redirect: entry.redirectEnd - entry.redirectStart, //重定向时间
        ttfb: entry.responseStart, //首宇节时间
        protocol: entry.nextHopProtocol, // 消求协议
        responseBodySize: entry.encodedBodySize, //购应内容大小
        responseHeaderSize: entry.transferSize - entry.encodedBodySize, // 将应头部大小
        transferSize: entry.transfersize, // 请求内容大小
        resourceSize: entry.decodedBodySize, //资源解压后的大人
        startTime: performance.now(),
      }

      // 数据上报
      lazyBatchReport(reportData)
    }
  }

  const observer = new PerformanceObserver(entryHandler)

  observer.observe({ type: ['resource'], buffered: true })
}

export default function observeEntries() {
  if (document.readyState === 'complete') {
    observeEvent()
  } else {
    const onLoad = () => {
      observeEvent()
      window.removeEventListener('load', onLoad, true)
    }
    window.addEventListener('load', onLoad, true)
  }
}
